//
//  ViewController.m
//  Voice2AlarmNote
//
//  Created by onemade on 14-10-24.
//  Copyright (c) 2014年 CNPC. All rights reserved.
//

#import "AlarmViewController.h"

@interface AlarmViewController ()

@end

@implementation AlarmViewController

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initControlsStyle];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - UITextView Delegate methods
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    return YES;
}
-(BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    //定义一个toolBar
    UIToolbar * topView = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];

    //设置style
    [topView setBarStyle:UIBarStyleDefault];
    
    //定义两个flexibleSpace的button，放在toolBar上，这样完成按钮就会在最右边
    UIBarButtonItem * button1 =[[UIBarButtonItem  alloc]initWithBarButtonSystemItem:                                        UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    
    UIBarButtonItem * button2 = [[UIBarButtonItem  alloc]initWithBarButtonSystemItem:                                        UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    
    //定义完成按钮
    UIBarButtonItem * doneButton = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStyleDone  target:self action:@selector(resignKeyboard)];
    UIBarButtonItem * recordButton = [[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStyleDone  target:self action:@selector(startListenning:)];
    recordButton.image = [UIImage imageNamed:@"microphone.png"];
    [recordButton setBackButtonBackgroundImage:[UIImage imageNamed:@"microphone.png"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [recordButton setTintColor:[UIColor blackColor]];
    [recordButton setWidth:20];
    //在toolBar上加上这些按钮
    NSArray * buttonsArray = [NSArray arrayWithObjects:button1,button2,recordButton,doneButton,nil];
    [topView setItems:buttonsArray];
    
    [textView setInputAccessoryView:topView];
    return YES;
}

#pragma mark - button actions
- (IBAction)ok:(id)sender {
//    [self dismissViewControllerAnimated:YES completion:^{}];
    if ([[self.contentTextView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] < 1) {
        [self.contentTextView becomeFirstResponder];
        self.contentTextView.text = [self.contentTextView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        return;
    }
    Alarm *alarm = nil;
    BOOL isSaveSuccess= NO;
    
    NSString *content = self.contentTextView.text;
    NSString *time = [self formatDate:[self.datePicker date]];
  
    if (self.isUpdate == NO) {
        if ([[AlarmTool sharedAlarmTool] isExistSameTimeAlarm:time] == YES) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"已存在相同时间的提醒，请另选其它时间" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            return;
        }
        alarm = [NSEntityDescription insertNewObjectForEntityForName:@"Alarm" inManagedObjectContext:[self appDelegate].managedObjectContext];
        int id = [[AlarmTool sharedAlarmTool] recieveLastObjectID] + 1;
        
        alarm.alarmTime = time;
        alarm.alarmContent = content;
        alarm.identifier = [NSNumber numberWithInt:id];
        isSaveSuccess = [[AlarmTool sharedAlarmTool] addAlarm:alarm];
        
    }else{
        self.currentAlarm.alarmContent = content;
        self.currentAlarm.alarmTime = time;
        isSaveSuccess = [[AlarmTool sharedAlarmTool] updateAlarm:self.currentAlarm];
    }
    if (isSaveSuccess == YES) {
        [self dismissViewControllerAnimated:YES completion:^{}];
    }
}
- (IBAction)cancelBTNPress:(id)sender {
     [self dismissViewControllerAnimated:YES completion:^{}];
}
//隐藏键盘
- (void)resignKeyboard {
    [self.contentTextView resignFirstResponder];
    [UIView animateWithDuration:1.0 animations:^{
        [self.containerScrollView setContentSize:CGSizeMake(self.containerScrollView.frame.size.width, self.view.frame.size.height)];
    }];
}
//录音按钮
- (void)startListenning:(id)sender
{
    [self.contentTextView resignFirstResponder];
    
    _popView = [[PopupView alloc] initWithFrame:CGRectMake(100, 300, 0, 0)];
    _popView.ParentView = self.view;
    //初始化语音识别控件
    _iflyRecognizerView = [[IFlyRecognizerView alloc] initWithCenter:self.view.center];
    _iflyRecognizerView.delegate = self;
    [_iflyRecognizerView setParameter: @"iat" forKey: [IFlySpeechConstant IFLY_DOMAIN]];
     [_iflyRecognizerView setParameter:@"plain" forKey:[IFlySpeechConstant RESULT_TYPE]];
    //asr_audio_path保存录音文件名,如不再需要,设置value为nil表示取消,默认目录是documents
    [_iflyRecognizerView setParameter:@"asrview.pcm " forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];
    //启动识别服务
    [_iflyRecognizerView start];
    
    NSLog(@"start listenning...");
}

#pragma mark IFlyRecognizerViewDelegate

/** 识别结果回调方法
 @param resultArray 结果列表
 @param isLast YES 表示最后一个，NO表示后面还有结果
 */
- (void)onResult:(NSArray *)resultArray isLast:(BOOL)isLast
{
    NSMutableString *result = [[NSMutableString alloc] init];
    NSDictionary *dic = [resultArray objectAtIndex:0];
    
    for (NSString *key in dic) {
        [result appendFormat:@"%@",key];
    }
    
    self.contentTextView.text = [NSString stringWithFormat:@"%@%@",self.contentTextView.text,result];
}

/** 识别结束回调方法
 @param error 识别错误
 */
- (void)onError:(IFlySpeechError *)error
{
    [self.view addSubview:_popView];
    
    [_popView setText:@"识别结束"];
    
    NSLog(@"errorCode:%d",[error errorCode]);
}

#pragma mark - customize methods
-(AppDelegate *)appDelegate
{
    return [[UIApplication sharedApplication] delegate];
}
-(void)initControlsStyle
{
    self.contentTextView.layer.borderColor = [UIColor darkGrayColor].CGColor;
    self.contentTextView.layer.borderWidth = 1;
    self.contentTextView.layer.cornerRadius = 5;
    self.contentTextView.delegate = self;
    
    self.datePicker.layer.borderColor = [UIColor darkGrayColor].CGColor;
    self.datePicker.layer.borderWidth = 1;
    self.datePicker.layer.cornerRadius = 5;
    
    self.okBTN.layer.cornerRadius = 2;
    self.cancelBTN.layer.cornerRadius = 2;
    
    self.containerScrollView.frame = self.view.frame;
}

-(NSString *)formatDate:(NSDate *)date
{
    NSDate *selected = date;
    // 创建一个日期格式器
    NSDateFormatter *dateFormatter =[[NSDateFormatter alloc] init];
    // 为日期格式器设置格式字符串
    [dateFormatter setDateFormat:@"yyyy/MM/dd HH:mm"];
    // 使用日期格式器格式化日期、时间
    NSString *destDateString = [dateFormatter stringFromDate:selected];
    
    return destDateString;
}
@end
